from django.shortcuts import render, redirect
from app01 import models
from django import forms
# 验证方式1：引入对模型的正则表达式
from django.core.validators import RegexValidator
# 验证方式2
from django.core.exceptions import ValidationError
# 后端代码安全标记到前端
from django.utils.safestring import mark_safe
#分页组件类
from app01.utils.pagination import Pagination

from app01.utils.bootstrap import BootStrapModelForm

from app01.utils.form import UserModelForm,PrettyModelForm,PrettyEditModelForm

#------------------用户管理----------------------------------------------------------
def user_list(request):
    """用户列表"""
    # 获取数据库表中的所有对象
    queryset = models.UserInfo.objects.all()
    page_object = Pagination(request,queryset,page_size=5)
    context = {
        "queryset": page_object.page_queryset,
        "page_string":page_object.html(),
    }
    return render(request, 'user_list.html',context)

def user_model_add(request):
    """添加用户（ModelForm）"""
    if request.method == "GET":
        # 类实例化
        form = UserModelForm()
        return render(request, 'user_model_add.html', {'form': form})
    #处理POST请求并校验数据
    form = UserModelForm(data=request.POST)
    if form.is_valid():#校验成功
        #数据合法，保存数据
        #{'name': '小样', 'password': '111', 'age': 11, 'account': Decimal('0'), 'create_time': datetime.datetime(2022, 10, 1, 0, 0, tzinfo=<UTC>), 'gender': 2, 'depart': <Department: 人力部>}
        #print(form.cleaned_data)
        form.save()
        return redirect("/user/list/")
    #校验失败,在页面上显示错误信息
    #print(form.errors)
    return render(request, 'user_model_add.html', {'form': form})

def user_delete(request):
    """删除用户"""
    uid = request.GET.get("uid")
    models.UserInfo.objects.filter(id=uid).delete()
    return redirect("/user/list/")

def user_model_edit(request, nid):
    #获取当前行数据
    row_object = models.UserInfo.objects.filter(id=nid).first()
    if request.method == "GET":
        #将默认值传递给页面
        form = UserModelForm(instance=row_object)
        return render(request, 'user_model_edit.html',{"form":form})
    #处理post请求
    form = UserModelForm(data=request.POST,instance=row_object)
    # 校验
    if form.is_valid():
        form.save()
        return redirect("/user/list/")
    return render(request,'user_model_edit.html',{"form":form})
